package com.ruoyi.zsyh.controller.applet.after.factory;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.zsyh.domain.*;
import com.ruoyi.zsyh.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * 服务订单 -- 全部订单
 */
@Controller
@RequestMapping("/applet/zsyh/serviceOrderFactory")
public class ZsyhServiceOrderFactoryAppletController extends BaseController
{

    @Autowired
    private IZsyhServiceOrderService zsyhServiceOrderService;

    @Autowired
    private IZsyhAfterProductMoneyService zsyhAfterProductMoneyService;

    @Autowired
    private IZsyhAfterFactoryService zsyhAfterFactoryService;

    @Autowired
    private IZsyhAfterFactoryBalanceService zsyhAfterFactoryBalanceService;

    @Autowired
    private IZsyhServiceOrderPartsService zsyhServiceOrderPartsService;

    @Autowired
    private IZsyhServiceOrderApplymoneyService zsyhServiceOrderApplymoneyService;

    @Autowired
    private IZsyhServiceOrderLogService zsyhServiceOrderLogService;

    @Autowired
    private IZsyhServiceOrderSettlementService zsyhServiceOrderSettlementService;

    @Autowired
    private IZsyhAfterServiceTypeService zsyhAfterServiceTypeService;

    @Autowired
    private IZsyhUserRepairareaService zsyhUserRepairareaService;

    /**
     * 获取服务分类
     * @return
     */
    @RequestMapping("/getServiceType")
    @ResponseBody
    public AjaxResult getServiceType(){
        List<ZsyhAfterServiceType> ztrees = zsyhAfterServiceTypeService.getServiceTypeTree();
        return success("成功", ztrees);
    }

    /**
     * 获取消息数量
     * @param factoryId
     * @return
     */
    @RequestMapping("/getOrderNum")
    @ResponseBody
    public AjaxResult getServiceType(String factoryId){
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setOrderState("203");
        order.setFactoryId(factoryId);
        List<ZsyhServiceOrder> list1 = zsyhServiceOrderService.selectZsyhServiceOrderList(order);

        ZsyhServiceOrderParts orderParts = new ZsyhServiceOrderParts();
        orderParts.setPartsState("1");
        orderParts.setFactoryId(factoryId);
        List<ZsyhServiceOrderParts> list2 = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(orderParts);

        orderParts.setPartsState("4");
        List<ZsyhServiceOrderParts> list4 = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(orderParts);

        orderParts.setPartsState("2");
        List<ZsyhServiceOrderParts> list5 = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(orderParts);

        ZsyhServiceOrderApplymoney orderApplymoney = new ZsyhServiceOrderApplymoney();
        orderApplymoney.setApplyState("1");
        orderApplymoney.setFactoryId(factoryId);
        List<ZsyhServiceOrderApplymoney> list3 = zsyhServiceOrderApplymoneyService.selectZsyhServiceOrderApplymoneyList(orderApplymoney);

        Map map = new HashMap();
        map.put("list1", list1.size());
        map.put("list2", list2.size());
        map.put("list3", list3.size());
        map.put("list4", list4.size());
        map.put("list5", list5.size());

        return success("成功", map);
    }


    /**
     * 厂家保存订单 挂起
     * @return
     */
    @RepeatSubmit
    @Transactional
    @RequestMapping("/suspendServiceOrder")
    @ResponseBody
    public AjaxResult suspendServiceOrder(String factoryId, String loginId, String userAddress, String userName, String userPhone, String orderAreaId,
                                              String serviceTypeId, String faultComment, long orderNumber, String afterProductTypeId, String afterProductId,String afterProductPaytime, String afterProductCode, String orderType,
                                          String partsInformation, String partsInformationNum, String isReturn,String logisticsId, String logisticsName, String logisticsNumber,
                                          String repairCheckMoney, String appendMoney, String refuseRepair
    )throws Exception
    {
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(IdWorker.getId());
        order.setOrderState("001");
        order.setOrderType(orderType);//订单分类 1个人订单 2厂家售后单 3保外订单 4厂家售后返修单
        order.setFactoryLoginId(loginId);
        order.setFactoryId(factoryId);
        order.setUserAddress(userAddress);
        order.setUserName(userName);
        order.setUserPhone(userPhone);
        order.setOrderAreaId(orderAreaId);
        order.setServiceTypeId(serviceTypeId);
        order.setFaultComment(faultComment);
        order.setOrderNumber(orderNumber);
        order.setAfterProductTypeId(afterProductTypeId);
        order.setAfterProductId(afterProductId);
        order.setAfterProductPaytime(afterProductPaytime);
        order.setAfterProductCode(afterProductCode);
        order.setWarrantyDate("6");

        if(EmptyUtils.isNotEmpty(repairCheckMoney))order.setRepairCheckMoney(new BigDecimal(repairCheckMoney));
        if(EmptyUtils.isNotEmpty(appendMoney))order.setAppendMoney(new BigDecimal(appendMoney));
        order.setRefuseRepair(refuseRepair);

        zsyhServiceOrderService.insertZsyhServiceOrder(order);

        //如果是已发配件，保存一个新的配件单
        if(EmptyUtils.isNotEmpty(partsInformation)){
            ZsyhServiceOrderParts orderParts = new ZsyhServiceOrderParts();
            orderParts.setId(IdWorker.getId());
            orderParts.setOrderId(order.getId());
            orderParts.setFactoryId(factoryId);
            orderParts.setPartsInformation(partsInformation);
            orderParts.setPartsInformationNum(Integer.valueOf(partsInformationNum));
            orderParts.setIsReturn(isReturn);
            orderParts.setLogisticsId(logisticsId);
            orderParts.setLogisticsName(logisticsName);
            orderParts.setLogisticsNumber(logisticsNumber);
            orderParts.setPartsState("3");//是否需要返回旧配件 1是 0否
            zsyhServiceOrderPartsService.insertZsyhServiceOrderParts(orderParts);
        }

        ZsyhServiceOrderLog log = new ZsyhServiceOrderLog();
        log.setId(IdWorker.getId());
        log.setOrderId(order.getId());
        log.setLogType("2");
        log.setLogContent("厂家保存订单");
        zsyhServiceOrderLogService.insertZsyhServiceOrderLog(log);
        return success("成功");
    }


    /**
     * 根据服务分类，产品id 获取需要支付的费用
     * @return
     */
    @RepeatSubmit
    @Transactional
    @RequestMapping("/getAfterProductMoney")
    @ResponseBody
    public AjaxResult getAfterProductMoney(String factoryId, String serviceTypeId, String afterProductId)throws Exception
    {

        if(EmptyUtils.isEmpty(afterProductId) || EmptyUtils.isEmpty(serviceTypeId)){
            return error("");
        }
        ZsyhAfterProductMoney productMoney = new ZsyhAfterProductMoney();
        productMoney.setServiceTypeId(serviceTypeId);
        productMoney.setProductId(afterProductId);
        List<ZsyhAfterProductMoney> productMoneyList = zsyhAfterProductMoneyService.selectZsyhAfterProductMoneyList(productMoney);
        if(productMoneyList.size() == 0){
            return error("下单的产品暂未设定费用。请完善后再下单");
        }
        productMoney = productMoneyList.get(0);
        BigDecimal frozenMoney = productMoney.getFrozenMoney();//下单需要冻结厂家的金额
        BigDecimal factoryMoney = productMoney.getFactoryMoney();//厂家需要支付的人工费
        BigDecimal repairMoney = productMoney.getRepairMoney();//需要支付给师傅的费用

        ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryId);
        BigDecimal factoryBalance = factory.getFactoryBalance();//厂家可用余额
        //判断可用余额是否充足
        if(factoryBalance.doubleValue() < frozenMoney.doubleValue()){
            return error("厂家可用余额不足，无法完成下单");
        }

        Map map = new HashMap();
        map.put("frozenMoney", frozenMoney);
        map.put("factoryMoney", factoryMoney);
        map.put("repairMoney", repairMoney);

        return success("成功", map);
    }

    /**
     * 厂家生成订单 厂家下单
     * @return
     */
    @RepeatSubmit
    @Transactional
    @RequestMapping("/generateServiceOrder")
    @ResponseBody
    public AjaxResult generateServiceOrder(String id, String factoryId, String loginId, String userAddress, String userName, String userPhone, String orderAreaId,
                                           String serviceTypeId, String faultComment, long orderNumber, String afterProductTypeId, String afterProductId,String afterProductPaytime, String afterProductCode, String orderType,
                                           String partsInformation, String partsInformationNum, String isReturn,String logisticsId, String logisticsName, String logisticsNumber,
                                           String repairCheckMoney, String appendMoney, String refuseRepair
    )throws Exception
    {
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(IdWorker.getId());
        order.setOrderState("0");
        order.setOrderType(orderType);
        order.setFactoryLoginId(loginId);
        order.setFactoryId(factoryId);
        order.setUserAddress(userAddress);
        order.setUserName(userName);
        order.setUserPhone(userPhone);
        order.setOrderAreaId(orderAreaId);
        order.setServiceTypeId(serviceTypeId);
        order.setFaultComment(faultComment);
        order.setOrderNumber(orderNumber);
        order.setAfterProductTypeId(afterProductTypeId);
        order.setAfterProductId(afterProductId);
        order.setAfterProductPaytime(afterProductPaytime);
        order.setAfterProductCode(afterProductCode);
        order.setWarrantyDate("6");
        order.setAppendMoney(BigDecimal.ZERO);

        ZsyhUserRepairarea repairarea = zsyhUserRepairareaService.selectAgentIdByAreaId(orderAreaId);
        if(repairarea != null){
            order.setRakerId(repairarea.getRepairId());
            order.setAgentId(repairarea.getAgentId());
        }


        if(EmptyUtils.isNotEmpty(repairCheckMoney))order.setRepairCheckMoney(new BigDecimal(repairCheckMoney));
        if(EmptyUtils.isNotEmpty(appendMoney))order.setAppendMoney(new BigDecimal(appendMoney));
        order.setRefuseRepair(refuseRepair);

        if("2".equals(orderType)){
            BigDecimal frozenMoney = BigDecimal.ZERO;
            BigDecimal factoryMoney = BigDecimal.ZERO;
            BigDecimal repairMoney = BigDecimal.ZERO;
            if(EmptyUtils.isNotEmpty(serviceTypeId)){
                ZsyhAfterProductMoney productMoney = new ZsyhAfterProductMoney();
                productMoney.setServiceTypeId(serviceTypeId);
                productMoney.setProductId(afterProductId);
                List<ZsyhAfterProductMoney> productMoneyList = zsyhAfterProductMoneyService.selectZsyhAfterProductMoneyList(productMoney);
                if(productMoneyList.size() == 0){
                    return error("下单的产品暂未设定费用。请完善后再下单");
                }
                productMoney = productMoneyList.get(0);
                frozenMoney = productMoney.getFrozenMoney();//下单需要冻结厂家的金额
                factoryMoney = productMoney.getFactoryMoney();//厂家需要支付的维修服务费
                repairMoney = productMoney.getRepairMoney();//给师傅的维修服务费
            }



            //实际冻结金额 等于下单的冻结金额 + 本单上门费 + 本单追加费用
            frozenMoney = new BigDecimal(frozenMoney.doubleValue() + order.getRepairCheckMoney().doubleValue() +  order.getAppendMoney().doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP);

            ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryId);
            BigDecimal factoryBalance = factory.getFactoryBalance();//厂家可用余额
            //判断可用余额是否充足
            if(factoryBalance.doubleValue() < frozenMoney.doubleValue()){
                return error("厂家可用余额不足，无法完成下单");
            }

            order.setOrderMoneyFactory(factoryMoney.add(order.getAppendMoney()));//厂家需要支付的维修服务费
            order.setOrderMoneyallFactory(new BigDecimal(factoryMoney.doubleValue() + order.getRepairCheckMoney().doubleValue() +  order.getAppendMoney().doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP));//厂家需要支付的 总金额
            order.setOrderMoneyRepair(repairMoney.add(order.getAppendMoney()));//给师傅的维修服务费
            order.setOrderMoneyallRepair(new BigDecimal(repairMoney.doubleValue() + order.getRepairCheckMoney().doubleValue() +  order.getAppendMoney().doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP));//给师傅的 总金额
            order.setOrderFrozenMoney(frozenMoney);//下单冻结厂家的费用

            //余额变动明细
            ZsyhAfterFactoryBalance balance = new ZsyhAfterFactoryBalance();
            balance.setFactoryId(factoryId);
            balance.setBalanceMoney(frozenMoney);
            balance.setBalanceClassify("2");//分类 1保证金明细 2余额明细
            balance.setBalanceType("5");//分类 1厂家自己充值 2后台充值 3余额扣除 4余额解冻  5余额冻结
            balance.setBalanceMoneyAfter(factoryBalance.subtract(frozenMoney).setScale(2, BigDecimal.ROUND_HALF_UP));
            balance.setOrderId(order.getId());
            zsyhAfterFactoryBalanceService.insertZsyhAfterFactoryBalance(balance);

            //减少厂家余额，增加冻结金额
            ZsyhAfterFactory _factory = new ZsyhAfterFactory();
            _factory.setId(factoryId);
            _factory.setFactoryBalance(factoryBalance.subtract(frozenMoney).setScale(2, BigDecimal.ROUND_HALF_UP));//减少余额
            _factory.setFactoryFreeze(factory.getFactoryFreeze().add(frozenMoney).setScale(2, BigDecimal.ROUND_HALF_UP));//增加保证金
            zsyhAfterFactoryService.updateZsyhAfterFactory(_factory);
        }

        if(EmptyUtils.isNotEmpty(id)){
            order.setId(id);
            zsyhServiceOrderService.updateZsyhServiceOrder(order);
        }else{
            zsyhServiceOrderService.insertZsyhServiceOrder(order);
        }


        //如果是已发配件，保存一个新的配件单
        if(EmptyUtils.isNotEmpty(partsInformation)){
            ZsyhServiceOrderParts orderParts = new ZsyhServiceOrderParts();
            orderParts.setId(IdWorker.getId());
            orderParts.setOrderId(order.getId());
            orderParts.setFactoryId(factoryId);
            orderParts.setPartsInformation(partsInformation);
            orderParts.setPartsInformationNum(Integer.valueOf(partsInformationNum));
            orderParts.setIsReturn(isReturn);
            orderParts.setLogisticsId(logisticsId);
            orderParts.setLogisticsName(logisticsName);
            orderParts.setLogisticsNumber(logisticsNumber);
            orderParts.setPartsState("3");//是否需要返回旧配件 1是 0否
            zsyhServiceOrderPartsService.insertZsyhServiceOrderParts(orderParts);
        }
        ZsyhServiceOrderLog log = new ZsyhServiceOrderLog();
        log.setId(IdWorker.getId());
        log.setOrderId(order.getId());
        log.setLogType("2");
        log.setLogContent("厂家下单");
        zsyhServiceOrderLogService.insertZsyhServiceOrderLog(log);
        return success("成功");
    }

    /**
     * 订单消息的数量
     * @param loginId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFactoryServiceOrderMessageNum")
    @ResponseBody
    public AjaxResult getFactoryServiceOrderMessageNum(String factoryId, String loginId)throws Exception
    {
        //orderState 订单状态 0未接单（厂家下单）1已接单 101已预约 102服务中 2已完成 201平台待审核 202厂家待审核 203待拨款 3已支付 4已评价 5已取消 501师傅申请取消 6系统自动取消
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setOrderState("203");
        order.setFactoryId(factoryId);
        List<ZsyhServiceOrder> orderList1 = zsyhServiceOrderService.selectZsyhServiceOrderList(order);//待结算工单数量

        ZsyhServiceOrderParts parts = new ZsyhServiceOrderParts();
        parts.setFactoryId(factoryId);
        parts.setPartsState("1");
        List<ZsyhServiceOrderParts> partsList1 = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(parts);//配件单 待审核

        ZsyhServiceOrderApplymoney applymoney = new ZsyhServiceOrderApplymoney();
        applymoney.setFactoryId(factoryId);
        applymoney.setApplyState("1");
        List<ZsyhServiceOrderApplymoney> applyMoneyList = zsyhServiceOrderApplymoneyService.selectZsyhServiceOrderApplymoneyList(applymoney);//费用单 待审核

        parts = new ZsyhServiceOrderParts();
        parts.setFactoryId(factoryId);
        parts.setPartsState("4");
        List<ZsyhServiceOrderParts> partsList2 = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(parts);//配件单返件待确认

        parts = new ZsyhServiceOrderParts();
        parts.setFactoryId(factoryId);
        parts.setPartsState("2");
        List<ZsyhServiceOrderParts> partsList3 = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(parts);//配件单代发货

        Map map = new HashedMap();
        map.put("orderListSize1", orderList1.size());
        map.put("partsListSize1", partsList1.size());
        map.put("partsListSize2", partsList2.size());
        map.put("partsListSize3", partsList3.size());
        map.put("applyMoneyListSize", applyMoneyList.size());

        return success("成功", map);

    }


    /**
     * 厂家 订单中心 各个订单状态列表
     * @param orderState 0新工单 1待预约 101待上门 102服务中 2已完成 202已修好待审核 203待结算 3已结算 001未发工单 5已取消工单
     * 订单状态 001厂家保存（未下单） 0未接单（厂家下单）1已接单 101已预约 102服务中  201平台待审核 202厂家待审核
     *                   2已完成 203待拨款 3已支付 4已评价 5已取消 501师傅申请取消
     *
     * @param factoryId
     * @param loginId
     * @param pageNum
     * @param pageSize
     * @param startDate 下单时间 开始日期
     * @param endDate 下单时间 结束日期
     * @param area 所属区域
     * @param orderId 工单号
     * @param isParts 是否包含有配件单 1是
     * @param isMoney 是否包含费用单 1是
     * @param orderType 订单分类 2保内 3保外 4返修
     * @param serviceTypeId 服务类型id
     * @param productTypeId 产品类型id
     * @param brand 品牌
     * @param model 型号
     * @param attribute 规格
     * @param userName 联系人
     * @param userPhone 联系方式
     * @param isReminder 是否催过单 1已催
     * @param refuseRepair 是否拒修 1是 0否
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFactoryServiceOrderList")
    @ResponseBody
    public AjaxResult getFactoryServiceOrderList(String factoryId, String loginId, String orderState, String pageNum, String pageSize, String isReminder,
                                          String startDate, String endDate, String area, String orderId, String isParts, String isMoney,String orderType,
                                          String serviceTypeId, String productTypeId, String brand, String model, String attribute, String userName, String userPhone,
                                          String refuseRepair
    )throws Exception
    {
        Map map = new HashedMap();
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setOrderState(orderState);
        order.setFactoryId(factoryId);
        order.setId(orderId);
        order.setOrderAreaId(area);
        order.setOrderType(orderType);
        order.setServiceTypeId(serviceTypeId);
        order.setAfterProductTypeId(productTypeId);
        order.setUserName(userName);
        order.setUserPhone(userPhone);
        order.setRefuseRepair(refuseRepair);

        map.put("beginCreateTime", startDate);
        map.put("endCreateTime", endDate);
        map.put("isParts", isParts);
        map.put("isMoney", isMoney);
        map.put("brand", brand);
        map.put("model", model);
        map.put("attribute", attribute);
        map.put("isReminder", isReminder);
        order.setParams(map);
        List<ZsyhServiceOrder> listSize = zsyhServiceOrderService.selectZsyhServiceOrderList(order);//首页订单列表
        int total = listSize.size();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        order.setParams(map);
        List<ZsyhServiceOrder> orderList = zsyhServiceOrderService.selectZsyhServiceOrderList(order);//首页订单列表

        return success("成功", orderList, total);
    }

    /**
     * 厂家 订单详情
     * @return
     */
    @RequestMapping("/getFactoryServiceOrderDetails")
    @ResponseBody
    public AjaxResult getFactoryServiceOrderDetails(String orderId)throws Exception
    {
        //主订单
        ZsyhServiceOrder order = zsyhServiceOrderService.selectZsyhServiceOrderById(orderId);

        String repairId = order.getRepairStoreId();

        //订单关联的配件单
        ZsyhServiceOrderParts parts = new ZsyhServiceOrderParts();
        parts.setOrderId(orderId);
        List<ZsyhServiceOrderParts> partsList = zsyhServiceOrderPartsService.selectZsyhServiceOrderPartsList(parts);

        //订单关联的配件单
        ZsyhServiceOrderApplymoney applymoney = new ZsyhServiceOrderApplymoney();
        applymoney.setOrderId(orderId);
        List<ZsyhServiceOrderApplymoney> applyMoneyList = zsyhServiceOrderApplymoneyService.selectZsyhServiceOrderApplymoneyList(applymoney);

        //订单操作日志
        ZsyhServiceOrderLog log = new ZsyhServiceOrderLog();
        log.setOrderId(orderId);
        List<ZsyhServiceOrderLog> logList = zsyhServiceOrderLogService.selectZsyhServiceOrderLogList(log);

        //工单费用信息
        ZsyhServiceOrderSettlement settlement = new ZsyhServiceOrderSettlement();
        settlement.setOrderId(orderId);
        settlement.setFeeType("1");
        List<ZsyhServiceOrderSettlement> settlementList = zsyhServiceOrderSettlementService.selectZsyhServiceOrderSettlementList(settlement);

        //判断厂家是否允许使用自购件 是否使用自购件 1是 0否
        String factoryId = order.getFactoryId();
        order.setIsSelfParts("0");
        if(EmptyUtils.isNotEmpty(factoryId)){
            ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryId);
            if(factory != null){
                order.setIsSelfParts(factory.getIsSelfParts());
            }
        }

        ZsyhServiceOrderApplymoney applymoney1 = new ZsyhServiceOrderApplymoney();
        applymoney1.setOrderId(orderId);
        applymoney1.setApplyType("1");
        List<ZsyhServiceOrderApplymoney> applymoney1List = zsyhServiceOrderApplymoneyService.selectZsyhServiceOrderApplymoneyList(applymoney1);
        if(applymoney1List.size() > 0){//已经申请过里程费
            order.setIsMileageFee("1");
        }else{//还没有申请过里程费
            order.setIsMileageFee("0");
        }

        order.setPartsList(partsList);
        order.setApplyMoneyList(applyMoneyList);
        order.setLogList(logList);
        order.setSettlementList(settlementList);

        return success("成功", order);
    }


    /**
     * 厂家催单
     * @return
     * @throws Exception
     */
    @RequestMapping("/reminderServiceOrder")
    @ResponseBody
    public AjaxResult reminderServiceOrder(String factoryId, String loginId, String orderId, String orderReminderContent)throws Exception
    {
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(orderId);
        order.setOrderReminderState("1");
        order.setOrderReminderContent(orderReminderContent);
        zsyhServiceOrderService.updateZsyhServiceOrder(order);

        ZsyhServiceOrderLog log = new ZsyhServiceOrderLog();
        log.setId(IdWorker.getId());
        log.setOrderId(orderId);
        log.setLogType("2");
        log.setLogContent("厂家催单");
        zsyhServiceOrderLogService.insertZsyhServiceOrderLog(log);
        return success("成功");
    }

    /**
     * 厂家审核订单
     * @param orderState 102拒绝 2通过
     * @param auditReasonRejection 驳回原因
     * @return
     * @throws Exception
     */
    @RequestMapping("/auditFactoryServiceOrder")
    @ResponseBody
    public AjaxResult auditFactoryServiceOrder(String factoryId, String loginId, String orderId, String orderState, String auditReasonRejection)throws Exception
    {
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(orderId);
        order.setOrderState(orderState);
        if("2".equals(orderState)){
            order.setOrderState("203");
        }
        order.setAuditReasonRejection(auditReasonRejection);
        order.setAuditFactoryTime(new Date());
        zsyhServiceOrderService.updateZsyhServiceOrder(order);

        ZsyhServiceOrderLog log = new ZsyhServiceOrderLog();
        log.setId(IdWorker.getId());
        log.setOrderId(orderId);
        log.setLogType("2");
        if("102".equals(orderState)){
            log.setLogContent("厂家驳回订单,驳回原因：" + auditReasonRejection);
        }
        if("2".equals(orderState)){
            log.setLogContent("厂家通过订单审核");
        }
        zsyhServiceOrderLogService.insertZsyhServiceOrderLog(log);
        return success("成功");
    }

    /**
     * 厂家 删除订单
     * @return
     * @throws Exception
     */
    @RequestMapping("/delFactoryServiceOrder")
    @ResponseBody
    public AjaxResult delFactoryServiceOrder(String id)throws Exception
    {
        ZsyhServiceOrder order = zsyhServiceOrderService.selectZsyhServiceOrderById(id);
        String orderState = order.getOrderState();
        String factoryId = order.getFactoryId();

        ZsyhAfterFactoryBalance balance = new ZsyhAfterFactoryBalance();
        balance.setOrderId(id);
        balance.setIsthaw("0");
        List<ZsyhAfterFactoryBalance> balances = zsyhAfterFactoryBalanceService.selectZsyhAfterFactoryBalanceList(balance);
        if(balances.size() > 0){
            balance = balances.get(0);
            BigDecimal balanceMoney = balance.getBalanceMoney();
            balance.setIsthaw("1");
            zsyhAfterFactoryBalanceService.updateZsyhAfterFactoryBalance(balance);

            ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryId);
            BigDecimal factoryBalance = factory.getFactoryBalance();//厂家可用余额


            //余额变动明细
            ZsyhAfterFactoryBalance balance1 = new ZsyhAfterFactoryBalance();
            balance1.setFactoryId(balance.getFactoryId());
            balance1.setBalanceMoney(balanceMoney);
            balance1.setBalanceClassify("2");//分类 1保证金明细 2余额明细
            balance1.setBalanceType("4");//分类 1厂家自己充值 2后台充值 3余额扣除 4余额解冻  5余额冻结
            balance1.setBalanceMoneyAfter(factoryBalance.add(balanceMoney).setScale(2, BigDecimal.ROUND_HALF_UP));
            balance1.setOrderId(order.getId());
            zsyhAfterFactoryBalanceService.insertZsyhAfterFactoryBalance(balance1);


            //减少厂家余额，增加冻结金额
            ZsyhAfterFactory _factory = new ZsyhAfterFactory();
            _factory.setId(factoryId);
            _factory.setFactoryBalance(factoryBalance.add(balanceMoney).setScale(2, BigDecimal.ROUND_HALF_UP));//减少余额
            _factory.setFactoryFreeze(factory.getFactoryFreeze().subtract(balanceMoney).setScale(2, BigDecimal.ROUND_HALF_UP));//增加保证金
            zsyhAfterFactoryService.updateZsyhAfterFactory(_factory);
        }
        if(!"001".equals(orderState) && !"0".equals(orderState) && !"5".equals(orderState)){
            return error("订单已有后续流程，无法删除");
        }
        zsyhServiceOrderService.deleteZsyhServiceOrderById(id);

        return success("成功");
    }

    /**
     * 发单区域统计图
     * @param factoryId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOrderAreaStatistics")
    @ResponseBody
    public AjaxResult getOrderAreaStatistics(String factoryId, String startDate, String endDate)throws Exception
    {
        List<Map> list = zsyhServiceOrderService.getOrderAreaStatistics(factoryId, startDate, endDate);
        return success("成功", list);
    }


    /**
     * 获取工单费用信息
     * @param factoryId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFactoryMoneyById")
    @ResponseBody
    public AjaxResult getFactoryMoneyById(String factoryId)throws Exception
    {

        //orderState 订单状态 0未接单（厂家下单）1已接单 101已预约 102服务中 2已完成 201平台待审核 202厂家待审核 203待拨款 3已支付 4已评价 5已取消 501师傅申请取消 6系统自动取消
        Map orderList1 = zsyhServiceOrderService.getMoneyAllList(null, factoryId, "203");//待结算工单金额
        Map orderList2 = zsyhServiceOrderService.getMoneyAllList(null, factoryId, "3");//已结算工单金额
        orderList1.put("type", "待结算工单");
        orderList2.put("type", "已结算工单");
        List<Map> list = new ArrayList<>();
        list.add(orderList1);
        list.add(orderList2);
        return success("成功", list);
    }


    /**
     * 进行中的暂时冻结数据
     * @param factoryId
     * @param loginId
     * @param pageNum
     * @param pageSize
     * @param orderId
     * @param area
     * @param serviceTypeId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOrderFreezeMoney")
    @ResponseBody
    public AjaxResult getOrderFreezeMoney(String factoryId, String loginId, String pageNum, String pageSize,
                                          String orderId,String area,String serviceTypeId)throws Exception
    {
        Map map = new HashedMap();
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setFactoryId(factoryId);
        order.setId(orderId);
        order.setOrderAreaId(area);
        order.setServiceTypeId(serviceTypeId);

        order.setParams(map);
        List<ZsyhServiceOrder> listSize = zsyhServiceOrderService.getOrderFreezeMoney(order);//首页订单列表
        int total = listSize.size();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        order.setParams(map);
        List<ZsyhServiceOrder> orderList = zsyhServiceOrderService.getOrderFreezeMoney(order);//首页订单列表

        return success("成功", orderList, total);
    }


    /**
     * 冻结资金解冻记录
     * @param factoryId
     * @param loginId
     * @param pageNum
     * @param pageSize
     * @param orderId
     * @param area
     * @param serviceTypeId
     * @return
     * @throws Exception
     */
    @RequestMapping("/getOrderThawMoney")
    @ResponseBody
    public AjaxResult getOrderThawMoney(String factoryId, String loginId, String pageNum, String pageSize,
                                          String orderId,String area,String serviceTypeId)throws Exception
    {
        Map map = new HashedMap();
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setFactoryId(factoryId);
        order.setId(orderId);
        order.setOrderAreaId(area);
        order.setServiceTypeId(serviceTypeId);

        order.setParams(map);
        List<ZsyhServiceOrder> listSize = zsyhServiceOrderService.getOrderThawMoney(order);//首页订单列表
        int total = listSize.size();
        if(EmptyUtils.isNotEmpty(pageNum) && EmptyUtils.isNotEmpty(pageSize)){
            int num = Integer.valueOf(pageNum);
            int size = Integer.valueOf(pageSize);
            num = (num - 1) * size;
            map.put("beginPos", num);
            map.put("pageSize", size);
        }
        order.setParams(map);
        List<ZsyhServiceOrder> orderList = zsyhServiceOrderService.getOrderThawMoney(order);//首页订单列表

        return success("成功", orderList, total);
    }


    /**
     * 订单中心 取消订单申请
     * @return
     * @throws Exception
     */
    @RequestMapping("/cancelServiceOrderFactory")
    @ResponseBody
    public AjaxResult cancelServiceOrderFactory(String orderId)throws Exception
    {
        ZsyhServiceOrder order = new ZsyhServiceOrder();
        order.setId(orderId);
        order.setOrderState("5");
        zsyhServiceOrderService.updateZsyhServiceOrder(order);


        ZsyhAfterFactoryBalance balance = new ZsyhAfterFactoryBalance();
        balance.setOrderId(orderId);
        balance.setIsthaw("0");
        List<ZsyhAfterFactoryBalance> balances = zsyhAfterFactoryBalanceService.selectZsyhAfterFactoryBalanceList(balance);
        if(balances.size() > 0){
            balance = balances.get(0);
            String factoryId = balance.getFactoryId();
            BigDecimal balanceMoney = balance.getBalanceMoney();
            balance.setIsthaw("1");
            zsyhAfterFactoryBalanceService.updateZsyhAfterFactoryBalance(balance);

            ZsyhAfterFactory factory = zsyhAfterFactoryService.selectZsyhAfterFactoryById(factoryId);
            BigDecimal factoryBalance = factory.getFactoryBalance();//厂家可用余额


            //余额变动明细
            ZsyhAfterFactoryBalance balance1 = new ZsyhAfterFactoryBalance();
            balance1.setFactoryId(balance.getFactoryId());
            balance1.setBalanceMoney(balanceMoney);
            balance1.setBalanceClassify("2");//分类 1保证金明细 2余额明细
            balance1.setBalanceType("4");//分类 1厂家自己充值 2后台充值 3余额扣除 4余额解冻  5余额冻结
            balance1.setBalanceMoneyAfter(factoryBalance.add(balanceMoney).setScale(2, BigDecimal.ROUND_HALF_UP));
            balance1.setOrderId(order.getId());
            zsyhAfterFactoryBalanceService.insertZsyhAfterFactoryBalance(balance1);


            //减少厂家余额，增加冻结金额
            ZsyhAfterFactory _factory = new ZsyhAfterFactory();
            _factory.setId(factoryId);
            _factory.setFactoryBalance(factoryBalance.add(balanceMoney).setScale(2, BigDecimal.ROUND_HALF_UP));//减少余额
            _factory.setFactoryFreeze(factory.getFactoryFreeze().subtract(balanceMoney).setScale(2, BigDecimal.ROUND_HALF_UP));//增加保证金
            zsyhAfterFactoryService.updateZsyhAfterFactory(_factory);
        }

        ZsyhServiceOrderLog log = new ZsyhServiceOrderLog();
        log.setId(IdWorker.getId());
        log.setOrderId(orderId);
        log.setLogType("2");
        log.setLogContent("厂家取消订单");
        zsyhServiceOrderLogService.insertZsyhServiceOrderLog(log);
        return success("成功");
    }
}
